package com.kx.hackathon.service.impl;

import com.kx.hackathon.service.HandlerService;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service("BaikeServiceImpl")
public class BaikeServiceImpl implements HandlerService {
    @Autowired
    OkHttpClient httpClient;
    public String baike(String word) throws IOException {
            String url = "https://baike.baidu.com/item/"+word;
        System.out.println(url);
        FormBody.Builder params = new FormBody.Builder();
        params.add("question",word);
        Request request = new Request.Builder()
                .url(url)
                .header("X-Requested-With","XMLHttpRequest")
                .post(params.build())//默认就是GET请求，可以不写
                .build();
        Response response = httpClient.newCall(request).execute();
        String res = response.body().string().split("<meta name=\"description\" content=\"")[1].split("\"")[0];
        return res;
    }

    @Override
    public String handle(String msg, String arg) {
        try {
            return baike(arg);
        } catch (Exception e) {
            return "哎呀，没找到这个百科";
        }
    }

    @Override
    public String init(String msg, String arg) {
        return null;
    }

    @Override
    public boolean needInit() {
        return false;
    }
}
